package servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Dao.UserInfoDao;
import entity.UserInfo;

/**
 * Servlet implementation class indexservlet
 */
@WebServlet("/indexservlet")
public class indexservlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public indexservlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        UserInfoDao userInfoDao = new UserInfoDao();
        try {
            UserInfo userInfo = userInfoDao.findUserByUsernameAndPassword(username, password);
            if (userInfo!= null) {
          
                String role = userInfo.getRole();
                if ("系统管理员".equals(role)) {
                    response.sendRedirect( "admin.jsp");
                } else if ("用户".equals(role)) {
                	request.getSession().setAttribute("userInfo", userInfo);
                    request.getRequestDispatcher("customer.jsp").forward(request, response);
                } else {
                	response.sendRedirect("customer.jsp");
                }
            } else {
                
                request.setAttribute("errorMsg", "用户名或密码错误");
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "数据库操作异常，请稍后重试");
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
